Fork me on GitHub

1. Two Sum

Easy

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

1
2
3
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

从头开始,准备使用Java再刷一遍题,Java 0基础,syntax,数据结构,慢慢感觉。

  1. Brute force
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] ans = new int[2];
for(int i=0; i<nums.length; i++){
for(int j=i+1; j<nums.length; j++){
if(nums[i]+nums[j]==target){
ans[0] = i;
ans[1] = j;
}
}
}
return ans;
}
}

Syntax:

  1. java和c++很像,都需要提前声明变量类型

  2. for循环的变量一定要记得声明类型

  3. new https://blog.csdn.net/ljheee/article/details/52235915

    Point originOne = new Point(23, 94);

    Rectangle rectOne = new Rectangle(originOne, 100, 200);

    Rectangle rectTwo = new Rectangle(50, 100);

    第一行创建了一个 Point 类的对象,第二个和第三个线创建一个Rectangle 矩形类的对象。

    这些陈述中的每一个都有三个部分(详细讨论):

    声明Declaration:粗体代码是将变量名称与对象类型关联的变量声明。

    实例化Instantiating :new关键字是一个java运算符,它用来创建对象。

    初始化Initialization:new运算符,随后调用构造函数(interface),初始化新创建的对象。

  4. Hash map

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> mem = new HashMap();
for(int i=0; i<nums.length; i++){
int sub = target-nums[i];
if(mem.containsKey(sub)){
return new int[]{i, mem.get(sub)};
}
mem.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> mem = new HashMap();
for(int i=0; i<nums.length; i++){
int sub = target-nums[i];
if(mem.containsKey(sub)){
return new int[]{i, mem.get(sub)};
}
mem.put(nums[i], i);
}
return new int[]{};
}
}
Shuolin Tian wechat
欢迎加我微信交流